#include "SegImageWrapper.h"

#include "vtkPointData.h"
#include "itkImageToVTKImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkImageFileWriter.h"
#include "itkExtractImageFilter.h"

#include <QMessageBox>
#include <QString>

SegImageWrapper::SegImageWrapper()
{
    m_WorkingSegmentation = NOT_CHOSEN;
    m_WorkingMaterial = NULL;

    m_HounsefieldMaterials = new Materials;
    m_HounsefieldMaterials->push_back(new Material(1, "Soft Tissue", 255, 0, 0, 1.050, -699, 100));// -699, 100));
    m_HounsefieldMaterials->push_back(new Material(2, "Bone", 0, 255, 0, 1.654, 101, 3000));
    m_HounsefieldMaterials->push_back(new Material(3, "Air", 0, 0, 255, 1.0, -1000, -700));

    m_MergeLabelMapFilter = MergeLabelMapFilterType::New();
    m_MergeLabelMapFilter->SetMethod(MergeLabelMapFilterType::AGGREGATE);
}

SegImageWrapper::~SegImageWrapper()
{
    if (m_SimpleAutomaticSegmentation)
        delete m_SimpleAutomaticSegmentation;
    if (m_HounsefieldMaterials)
        delete m_HounsefieldMaterials;
}

void
SegImageWrapper::SeedPointPicked(double x, double y, double z)
{
    LabelMapPointer labelMap;

    switch(m_WorkingSegmentation)
    {
    case THRESHOLD_AUTOMATIC:
    {
        m_SimpleAutomaticSegmentation = new SimpleAutomaticSegmentation(m_WorkingMaterial);
        m_SimpleAutomaticSegmentation->Initialize(m_GreyImage, x, y, z);
        labelMap = m_SimpleAutomaticSegmentation->GetOutput();
        break;
    }
    default:
    {
        (new QErrorMessage())->showMessage("The segmentation type is not chosen!");
        return;
    }
    }

     if (!labelMap.IsNull())
    {
        LabelMapPointer volume;

        if (m_WorkingMaterial->GetVolume().IsNull())
        {
            volume = LabelMapType::New();
            volume->CopyInformation(labelMap);
            volume->SetRegions(labelMap->GetLargestPossibleRegion());
            volume->AddLabelObject(labelMap->GetNthLabelObject(0));
        }
        else
        {
            volume = m_WorkingMaterial->GetVolume();
            m_MergeLabelMapFilter->SetInput(volume);
            m_MergeLabelMapFilter->SetInput(1, labelMap);
            m_MergeLabelMapFilter->Update();

            volume = m_MergeLabelMapFilter->GetOutput();
            volume->CopyInformation(m_MergeLabelMapFilter->GetOutput());
            volume->SetRegions(m_MergeLabelMapFilter->GetOutput()->GetLargestPossibleRegion());
        }

        m_WorkingMaterial->SetVolume(volume);
     }         
}



